﻿namespace JunFan.Tests.UITests
{
    using System;
    using System.Collections.Generic;
    using Domain;
    using FluentAssertions;
    using Infrastructure;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using OpenQA.Selenium;
    using OpenQA.Selenium.IE;
    using ViewModels;

    [TestClass]
    public class DashboardTests
    {
        [TestMethod]
        public void DisplayBacklogItems()
        {
            IEnumerable<Item> backLogItems = Given.NewItem.Build(5).Add();
            var createdBacklogItems = AutoMapper.Mapper.Map<IEnumerable<ItemView>>(backLogItems);

            Given.StartedItem.Build(4).Add();
            Given.CompletedItem.Build(7).Add();

            Dashboard dashboard = Dashboard.Open();

            IEnumerable<ItemView> backLogItemsShown = dashboard.GetBackLogItems();
            
            backLogItemsShown.ShouldAllBeEquivalentTo(createdBacklogItems, option => option.Excluding(itm => itm.InternalId));

            dashboard.Close();
        }
    }

    public class Dashboard
    {
        private InternetExplorerDriver _browser;

        private Dashboard() {}

        public static Dashboard Open()
        {
            var dashboard = new Dashboard();

            dashboard.OpenBrowser();

            return dashboard;
        }

        private void OpenBrowser()
        {
            _browser = new InternetExplorerDriver();

            _browser.Navigate().GoToUrl("http://localhost:52953/item");
        }

        public void Close()
        {
            if (_browser != null) _browser.Close();
        }

        public IEnumerable<ItemView> GetBackLogItems()
        {
            var backLogItems = new List<ItemView>();

            var table = _browser.FindElementById("backlogItems");

            var rows = table.FindElements(By.TagName("tr"));

            // supports table with header only
            for (int i = 1; i < rows.Count; i++)
            {
                var row = rows[i];
                var cols = row.FindElements(By.XPath(@"//td"));

                var item = new ItemView
                    {
                        Id = cols[0].Text,
                        Description = cols[1].Text,
                        CreatedOn = Convert.ToDateTime(cols[2].Text),
                        LeadTime = Convert.ToInt32(cols[3].Text)
                    };

                backLogItems.Add(item);
            }
            return backLogItems;
        }
    }
}